/**
 * 财务中心 - 收支对账
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    require("pagination");
    var angular = require("angular");
    require("angular-ui");
    var util = require("util");
    var ui = require("ui");
    var dialog = require("dialog");
    var tmpl = require("tmpl");
    require("angular-interceptor"); // 接管 ajax 错误处理
    require('authorize');
    require("permission");
    require('global');

    var app = angular.module('app', ['ngUI', 'ngInterceptor']);
    var api_prefix = G_CONFIG["api_prefix"] + "qmyx/brokerage/"; //api前缀

    // 查询服务
    function filterService($http) {
        var service = {
            data: [],
            hasData: true,
            pageIndex: 1,
            total : 0,
            field: "cst_name",
            // 搜索关键字
            searchValue: "",
            // 查询参数
            queryParam: {},
            doQuery: function (pageIndex) {
                service.pageIndex = service.queryParam.pageIndex = pageIndex || 1;
                service.queryParam.pageSize = service.pageSize;

                var url = api_prefix + 'getlist';
                $http.get(url,{params:service.queryParam})
                        .success(function (data) {
                            service.data = data.data.data;
                            service.total = data.data.total;
                            if( service.total === 0){
                                $(".no-data").show();
                                return
                            }else{
                                $(".no-data").hide();
                            }
                        })
                        .finally(function () {
                            service.queryParam = jQuery.parseJSON(service.queryParam);
                        });
            },
            parseParam: function(param, key){
                var paramStr="";
                if(param instanceof String||param instanceof Number||param instanceof Boolean){
                    paramStr+="&"+key+"="+encodeURIComponent(param);
                }else{
                    $.each(param,function(i){
                        var k=key==null?i:key+(param instanceof Array?"["+i+"]":"."+i);
                        paramStr+='&'+service.parseParam(this, k);
                    });
                }
                return paramStr.substr(1);
            },
            // 导出
            exportData: function () {
                var token = util.getToken();
                var field = service.field;
                this.queryParam[field] = this.searchValue;
                var filters = this.queryParam;
                
                var param = this.parseParam(filters)
                var url = api_prefix + 'export-ep&token='+token+"&"+param;
                window.location.href = url;
            },
            // 普通查询
            queryData: function () {
                var field = service.field;
                this.queryParam = {
                        pageIndex: this.pageIndex,
                        pageSize: this.pageSize,
                        //cst_name: this.searchValue,
                        isException:1,
                        brokerage_type:2,
                        p_projectId : this.projectId
                };
                this.queryParam[field] = this.searchValue;
                this.doQuery();
            },
            // 收集每位联名客户的成交佣金笔数
            lmArr : [],
            // 收集每位联名客户的默认数据
            defaultParam : [],
            // 选中某个联名客户的索引
            indexCustomer: 0,
            recordArr:[],
            recordNum:0,
            recordLength:0,
            getRecord: function (record) {
                var _this = this;
                var num = 0;
                var token = util.getToken();
                var recordIdArr = [];
                var len = record.lmInfoArr.length;
                this.lmArr = [];
                this.defaultParam = [];
                this.recordArr= [];
                this.recordLength = len;
                for( var i=0; i<len; i++){
                    var obj = {
                        cst_id:record.lmInfoArr[i].cst_id,
                        regbroker_id:record.lmInfoArr[i].regbroker_id,
                        room:record.room,
                        proj_id:record.proj_id,
                        cst_proj_id: record.lmInfoArr[i].cst_proj_id,
                        token: token,
                        brokerage_type: 2
                    };
                    this.defaultParam.push(obj);
                    var recordId = record.lmInfoArr[i].b_regbroker_cst_trade_recordId;
                    recordIdArr.push(recordId);
                } 
                this.recordArr = recordIdArr;
                this.getRecordList(recordIdArr[0]);       
            },
            showRecord: function (record, dialog, dialogScope) {
                setTimeout(function () {
                    dialog.reset();
                }, 20);
            },
            
            getRecordList: function (record) {
                var _this = this;
                var url = api_prefix + 'get-cj-multi-brokerage&b_regbroker_cst_trade_recordId=' + record;
                $http.get(url)
                        .success(function (data) {
                           _this.lmArr.push(data.data);
                           _this.recordNum++;
                           
                           if(_this.recordNum !== _this.recordLength){
                                _this.getRecordList(_this.recordArr[_this.recordNum])
                           }else{
                                _this.recordNum=0;
                                _this.recordLength=0;
                                _this.setRecord();
                           }
                        })
            },
            // 设置选中的ui样式
            setRecord: function () {
                var arr = this.lmArr;
                var isDefaule = true;
                var canSelect = true;
                for( var i=0, len=arr.length; i<len; i++){
                    if(arr[i].isoffer===1){
                        $("#lmList li").eq(i).addClass("lm-selected");
                        this.initTable(arr[i].data);
                        canSelect = false;
                        break;
                    }
                    if(arr[i].isApproval===1){
                        $("#lmList li").eq(i).addClass("lm-selected");
                        this.initTable(arr[i].data);
                        isDefaule = false;
                        break;
                    }
                }
                if(canSelect){
                    this.bindEvent();
                }
                if(isDefaule){
                    $("#lmList li").eq(0).addClass("lm-selected");
                    this.initTable(arr[0].data);
                }

            },
            initTable:function(list){
                var html = tmpl('brokerage_tmpl', {list: list});
                $("#myform").html(html);
                this.bindInputEvent();
                this.setInput(list);
            },
            // 收集要保存的数据
            collectData: function () {
                var batch = [];
                // 获取对应联名客户的数据
                var arr = this.lmArr[this.indexCustomer].data;
                var input = $("#myform input");
                for( var i=0, len=arr.length; i<len; i++){
                    var empty = {};
                    var param = $.extend(empty, this.defaultParam[this.indexCustomer]);
                    param.b_regbroker_brokerageId = arr[i].b_regbroker_brokerageId;
                    param.amount = parseInt(input.eq(i).val());
                    batch.push(param);
                }
                return batch;
            },
            // 收集要保存的不通过的数据
            collectFailData: function () {
                var allFail = [];
                // 获取不通过的联名客户的数据
                var arr = this.lmArr;
                for( var i=0, len=arr.length; i<len; i++){
                    //var batch = [];
                    if(i===this.indexCustomer){
                        continue
                    }else{
                        var arrCustom = arr[i].data;
                        for( var j=0, len2=arrCustom.length; j<len2; j++){
                            var empty = {};
                            var param = $.extend(empty, this.defaultParam[i]);
                            param.isoffer = arrCustom[j].isoffer;
                            param.brokerage_name = arrCustom[j].brokerage_name;
                            param.amount = 0;
                            param.orders = j+1;
                            param.approve_fail_reason = "联名购房";
                            param.approve_fail_type = 1;
                            allFail.push(param);
                        }
                        //allFail.push(batch);
                    } 
                }
                return allFail;
            },
            // 确定保存
            lmBuy: function () {
                var bool, _this = this;
                bool = this.checkForm();
                if(bool){
                    var token = util.getToken();
                    var url = api_prefix + "approval&token="+token;
                    var data = {};
                    data.batch = this.collectData();
                    data.brokerage_type = 2;
                    data.isException = 1;
                    data.recordId = this.recordArr[this.indexCustomer];
                    //this.submitFail();
                    $http.post(url, data).then(function () {
                        _this.doQuery();
                    });
                }
                return bool;
            },
            bindEvent: function () {
                var _this = this;
                $("#lmList li").on("click", function(){
                    $("#lmList li").removeClass("lm-selected");
                    $(this).addClass("lm-selected");
                    var index = $(this).index();
                    _this.indexCustomer = index;
                    _this.initTable(_this.lmArr[index].data);
                    //_this.setInput(_this.lmArr[index].data);
                });
            },
            // 绑定输入框的输入事件
            bindInputEvent: function () {
                var input = $("#myform input");
                var reg = /^\d+$/;
                input.each(function(i,item){
                    // 过滤输入的错误数据
                    $(item).on("keyup",function(){
                        var new_value = $(this).val();
                        if($.trim(new_value)===''){
                            return
                        }
                        // 匹配格式是否正确
                        if(!reg.test(new_value)){
                            // 去掉不合法的字符
                            new_value = new_value.replace(/[^\d]/g,"");
                            $(this).val(new_value);
                        }
                    });
                });
            },
            // 设置输入框里的佣金是否可修改
            setInput: function (arr) {
                var input = $("#myform input");
                for( var i=0, len=arr.length; i<len; i++){
                    if(arr[i].isoffer !== "0" || arr[i].isApproval !== "0"){
                        input.eq(i).attr("disabled",true); 
                    }
                }
            },
            // 检查表单
            checkForm: function () {
                var _this = this;
                this.hideError();
                var bool = true;
                var input = $("#myform input");
                input.each(function(i,item){
                    // 过滤输入的错误数据
                    var val = $(this).val();
                    var temp = /^\d+(\.\d+)?$/;
                    if(temp.test(val)==false){
                        _this.showError($(this),"请填写正确的数字");
                        bool = false;
                        return;
                    }
                });
                return bool;
            },
            showError:function(fieldId,msg){
                var validTemp = $('<p class="c-red js-err lh30"></p>'); //验证信息
                validTemp.html(msg);
                fieldId.parent().append(validTemp);
            },
            hideError:function(){
                $('.js-err').remove();
            },
            projectId : '',
            // 项目列表
            projectList : [],
            getProjects : function(){
                return $http.get('/api/index.php?r=qmyx/customer-manage/get-project-list')
            },
            projectChanged : function(){
                this.queryData();
            }
        }
        return service;
    }
    app.factory('filters', ['$http', filterService]);

    function queryService($scope, filters) {
        $scope.data = filters;
        setTimeout(function() {
            filters.getProjects().then(function(res){
                filters.projectList = res.data.data;
                //filters.queryData();
            });
        }, 0);
        $scope.exportData = function () {
            filters.exportData();
        }
    };
    app.controller('queryService', ['$scope', 'filters', queryService])

    angular.bootstrap(document, ['app']);
});